package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.repository.StrategyCommentMongoRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import cn.wolfcode.luowowo.common.query.StrategyQuery;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Optional;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {
    @Autowired
    private StrategyCommentMongoRepository repository;

    @Override
    public AjaxResult save(StrategyComment entity) {
        AjaxResult ajaxResult = new AjaxResult();
        try {
            repository.save(entity);
        } catch (Exception e) {
            ajaxResult.mark(e.getMessage());
        }
        return ajaxResult;
    }

    @Override
    public Page<StrategyComment> query(StrategyQuery qo) {
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize());
        return repository.findByDetailId(qo.getDetailId(), pageable);
    }

    @Override
    public AjaxResult commentThumbUp(String toId, Long fromId) {
        AjaxResult jsonResult = new AjaxResult();
        try {
            Optional<StrategyComment> op = repository.findById(toId);
            op.ifPresent(comment->{
                //取出评论列表
                List<Long> thumbuplist = comment.getThumbuplist();
                //判断是否列表中已经存在
                if (thumbuplist.contains(fromId)) {
                    //存在就是取消
                    thumbuplist.remove(fromId);
                } else {
                    //没有就是点赞
                    thumbuplist.add(fromId);
                }
                //设置点赞数
                comment.setThumbupnum(thumbuplist.size());
                //更新改评论
                repository.save(comment);
            });
        }catch (Exception e){
            jsonResult.mark(e.getMessage());
        }
        return jsonResult;
    }
}
